# Author: Chris Moyer
import os
import copy

from jinja2 import Environment, FileSystemLoader, PackageLoader, ChoiceLoader

import marajo

template_dirs = []


def rst(s):
    """
    Add in the restructured text filter.
    This was in Jinja1.1, but somehow got lost in jinja2
    """
    import urllib
    from docutils.core import publish_parts
    try:
        s = str(s.encode("utf-8"))
        try:
            parts = publish_parts(source=s, writer_name='html4css1')
            return str(parts['fragment'])
        except:
            return "<code>%s</code>" % s
    except:
      return "Error decoding comment"


def render(template_path, template_dict={}, debug=False, template_dirs=template_dirs):
    """Renders the template at the given path with the given dict of values.

    Example usage:
        render("templates/index.html", {"name": "Bret", "values": [1, 2, 3]})

    Args:
        template_path: path to a Django template
        template_dict: dictionary of values to apply to the template
    """
    template_dict['version'] = marajo.config.get("version")
    template_dict['application'] = marajo.config.get("application")

    # We add some stuff to the template dictionary
    env = Environment(loader=ChoiceLoader([
                                    FileSystemLoader(template_dirs),
                                    PackageLoader("marajo.appengine", "templates")
                                ])
                            )
    env.filters['rst'] = rst
    t = env.get_template(template_path)
    return t.render(**template_dict)
